<template>
  <div class="upload">
    <el-upload
      ref="uploadRef"
      v-model:file-list="defaultFileList"
      :accept="accept"
      :action="action"
      :auto-upload="false"
      class="upload-content"
      :close-on-click-modal="false"
      :data="data"
      :disabled="!editable"
      :limit="limit"
      list-type="picture-card"
      :multiple="true"
      :name="name"
      :on-change="handleChange"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-progress="handleProgress"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
    >
      <template #trigger>
        <vab-icon icon="add-line" />
      </template>
      <el-dialog v-model="dialogVisible" append-to-body title="查看大图">
        <div>
          <el-image :src="dialogImageUrl" />
        </div>
      </el-dialog>
    </el-upload>
  </div>
</template>

<script>
import _ from "lodash";
import { failMsg } from "@/utils/MessageUtils";

export default defineComponent({
  name: "UploadImgEmbed",
  props: {
    limit: {
      type: Number,
      default: 10,
      required: true
    },
    accept: {
      type: String,
      default: "image/png, image/jpeg"
    },
    defaultfilelist: {
      type: Array,
      default: () => {
        return [];
      }
    },
    editable: {
      type: Boolean,
      default: true
    },
    size: {
      type: Number,
      default: 1024,
      required: true
    }
  },
  setup(props) {
    const state = reactive({
      uploadRef: null,
      name: "UploadImgEmbed",
      show: false,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      draggable: true,
      editable: true,
      action: "",
      fileList: [],
      defaultFileList: [],
      delFileList: [],
      picture: "picture",
      imgNum: 0,
      imgSuccessNum: 0,
      imgErrorNum: 0,
      typeList: null,
      title: "上传",
      accept: "image/png, image/jpeg",
      limit: "5",
      data: {}
    });

    state.accept = ref(props.accept);
    state.limit = ref(props.limit);
    state.defaultFileList = ref(props.defaultfilelist);
    state.editable = ref(props.editable);
    state.size = ref(props.size);

    const handleProgress = () => {
      state.loading = true;
      state.show = true;
    };
    const handleChange = file => {
      if (file.size > state.size) {
        failMsg(`文件大于${state.size}B`);
        //state['uploadRef'].uploadFiles.splice(0, 1)
        state["uploadRef"].handleRemove(file);
        return false;
      } else {
        state.fileList.push(file);
        return true;
      }
    };
    const handleRemove = file => {
      state.imgNum = state.imgNum - 1;
      state.allNum = state.allNum - 1;
      if (file.raw == null) {
        state.delFileList.push(file);
      }
      const newFile = [];
      state.fileList.forEach(f => {
        if (f.uid != file.uid) {
          if (f.raw != null) {
            newFile.push(f);
          }
        }
      });
      state.fileList = newFile;
    };

    const getFileList = () => {
      return { fileList: state.fileList, delList: state.delFileList };
    };

    const handleSuccess = (response, file, fileList) => {
      state.imgNum = state.imgNum + 1;
      state.imgSuccessNum = state.imgSuccessNum + 1;
      if (fileList.length === state.imgNum) {
        setTimeout(() => {
          failMsg(`上传完成! 共上传${fileList.length}张图片`);
        }, 1000);
      }

      setTimeout(() => {
        state.loading = false;
        state.show = false;
      }, 1000);
    };
    const handleError = (err, file) => {
      state.imgNum = state.imgNum + 1;
      state.imgErrorNum = state.imgErrorNum + 1;
      failMsg(`文件[${file.raw.name}]上传失败,文件大小为${_.round(file.raw.size / 1024, 0)}KB`);
      setTimeout(() => {
        state.loading = false;
        state.show = false;
      }, 1000);
    };

    const handlePreview = file => {
      state.dialogImageUrl = file.url;
      state.dialogVisible = true;
    };
    const handleExceed = files => {
      failMsg(`当前限制选择 ${state.limit} 个文件，本次选择了${files.length}个文件`);
    };

    const percentage = computed(() => {
      if (state.allImgNum === 0) return 0;
      return _.round(state.imgNum / state.allImgNum, 2) * 100;
    });

    watch(
      () => props.defaultfilelist,
      newVal => {
        state.defaultFileList = ref(newVal);
        state.fileList = [];
      }
    );

    return {
      ...toRefs(state),
      handleProgress,
      handleChange,
      handleSuccess,
      handleError,
      handleRemove,
      handlePreview,
      handleExceed,
      percentage,
      getFileList
    };
  }
});
</script>

<style lang="scss" scoped>
.upload {
  .upload-content {
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }
    :deep() {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px;
        border: 2px dashed #c0ccda;
        .ri-add-line {
          font-size: 24px;
        }
      }
      .el-upload-list--picture {
        margin-bottom: 20px;
      }
      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px;
        }
      }
    }
  }
}
</style>
